package com.jzg.sys.common.rest;

import com.alibaba.fastjson.JSONObject;
import com.jzg.sys.common.util.CommonUtils;
import com.jzg.sys.common.vo.ResultVO;
import com.jzg.sys.dao.entity.SecUser;
import com.jzg.sys.manager.BaseCacheManager;
import com.jzg.sys.manager.SecUserManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/loginRest")
@Api(value = "loginRest", description = "登录接口")
public class LoginRest extends  BaseRest {
    @Autowired
    private SecUserManager userManager;
    @Autowired
    private BaseCacheManager cacheService;
    @Value("${cus.timeout}")
    private int timeout;

    @ApiOperation(value = "普通登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO login(
            @ApiParam(value = "账号", required = true) @RequestParam String userCode,
            @ApiParam(value = "密码", required = true) @RequestParam String password,
            @ApiParam(value = "临时token", required = true) @RequestParam String tempToken,
            @ApiParam(value = "验证码", required = true) @RequestParam String kaptcha) {
        if(!cacheService.hasKey(tempToken,sysCode)){
            return  new ResultVO(false,"验证码错误或过期");
        }
        Object key = cacheService.get(tempToken, sysCode);
		if(key ==null || StringUtils.isBlank(kaptcha)){
			return new ResultVO(false,"验证码为空");
		}
		String code = key.toString();
		if(!StringUtils.equalsIgnoreCase(kaptcha, code)){
			return new ResultVO(false,"验证码错误");
		}
        SecUser secUser = userManager.findUserByCode(userCode,sysCode);
        if(secUser ==null || !secUser.getIsValid()){
            return new ResultVO(false,"账号不存在");
        }
		SecUser bizUser = userManager.getById(secUser.getUserId());
        if(!DigestUtils.md5Hex(password).equals(secUser.getPassword())){
            return new ResultVO(false,"账号或密码错误");
        }
        String token = DigestUtils.md5Hex(CommonUtils.getUUID()+ sysCode);
        clearOldUser(secUser.getUserId()+"01");
        JSONObject obj = new JSONObject();
        obj.put("token",token);
        obj.put("userId",secUser.getUserId());
        obj.put("userName",secUser.getUserName());
        obj.put("userCode",secUser.getUserCode());
        obj.put("user", bizUser);
        cacheService.put(token,obj,sysCode,timeout*60l);
        cacheService.hasKey(token,sysCode);
        Object objjj = cacheService.get(token,sysCode);
        //存储账号和token关系，便于索引
		cacheService.put(secUser.getUserId(), token, sysCode,timeout*60l);
        ResultVO vo = new ResultVO(true,"登录成功");
        vo.setObj(obj);
        return vo;
    }

    /**
    * @Title: loginOut
    * @Description: 退出清除token
    * @param token
    * @return
    * @Author: lzp 李志鵬
    * @Date: 2018/2/25
    */
    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public void loginOut(@RequestHeader("token") String token){
        if(cacheService.hasKey(token,sysCode)){
            cacheService.remove(token,sysCode);
        }
    }

    /** 
	 * @Title: clearOldUser 
	 * @Description: 当用户在第二台手机上登录时，清理掉原来token信息和极光注册信息 
	 * @param userId
	 * @author 李志鹏 lzp  
	 * @date 2016年9月21日 下午6:50:08 
	 */
	private void clearOldUser(String userId) {
		Object obj = cacheService.get(userId, sysCode);
		if(obj!=null){
			String token = obj.toString();
			cacheService.remove(userId, sysCode);
			cacheService.remove(token, sysCode);
		}
	}

	@ApiOperation(value = "判断token是否有效")
    @RequestMapping(value = "/isTokenValid", method = RequestMethod.GET)
    @ResponseBody
    public Boolean isTokenValid(@RequestHeader("token") String token){
        if(cacheService.hasKey(token,sysCode)){
            return true;
        }else{
        	return false;
        }
    }
}
